package com.farm.web.tag;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;


public class BasePathTaget extends TagSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	static final Logger log = Logger.getLogger(BasePathTaget.class);
	@Override
	public int doEndTag() throws JspException {
		return 0;
	}

	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) this.pageContext
				.getRequest();
		String path = request.getContextPath();
		//获取https
		String scheme = request.getHeader("X-Forwarded-Scheme");
		if (scheme == null || "".equals(scheme) || "null".equalsIgnoreCase(scheme)) {
		    scheme = request.getScheme();
		}
		int serverPort = request.getServerPort();
		
		//String basePath = request.getScheme() + "://" + request.getServerName()
		String basePath =  scheme + "://" + request.getServerName();
		//80就不用加端口，以免nginx报错 net::ERR_SSL_PROTOCOL_ERROR
		if (serverPort != 80) {
		    basePath += ":" + request.getServerPort();
        }
		basePath +=  path + "/";
		JspWriter jspw = this.pageContext.getOut();
		try {
			jspw.print(basePath);
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		return 0;
	}
}
